package handler

import (
	"github.com/gin-gonic/gin"
	pp "lab-service/proto/post"
	"net/http"
)

type Post struct {
	PostClient pp.PostService
}

func (p *Post) One(ctx *gin.Context) {
	form := new(pp.PostRequest)
	if err := ctx.Bind(form); err != nil {
		ctx.AbortWithStatus(http.StatusBadRequest)
		return
	}

	rsp, err := p.PostClient.One(ctx, form)
	if err != nil {
		ctx.AbortWithStatusJSON(http.StatusBadRequest, err)
		return
	}

	ctx.JSON(http.StatusOK, rsp)
}

func (p *Post) Page(ctx *gin.Context) {
	form := new(pp.PostRequest)
	if err := ctx.Bind(form); err != nil {
		ctx.AbortWithStatus(http.StatusBadRequest)
		return
	}
	form.Enable = true

	rsp, err := p.PostClient.Page(ctx, form)
	if err != nil {
		ctx.AbortWithStatusJSON(http.StatusBadRequest, err)
		return
	}

	ctx.JSON(http.StatusOK, rsp)
}

// only admin
func (p *Post) PageAll(ctx *gin.Context) {
	form := new(pp.PostRequest)
	if err := ctx.Bind(form); err != nil {
		ctx.AbortWithStatus(http.StatusBadRequest)
		return
	}

	rsp, err := p.PostClient.Page(ctx, form)
	if err != nil {
		ctx.AbortWithStatusJSON(http.StatusBadRequest, err)
		return
	}

	ctx.JSON(http.StatusOK, rsp)
}

func (p *Post) PageMe(ctx *gin.Context) {
	form := new(pp.PostRequest)
	if err := ctx.Bind(form); err != nil {
		ctx.AbortWithStatus(http.StatusBadRequest)
		return
	}
	form.Uid = ctx.Value("uid").(int64)

	rsp, err := p.PostClient.Page(ctx, form)
	if err != nil {
		ctx.AbortWithStatusJSON(http.StatusBadRequest, err)
		return
	}

	ctx.JSON(http.StatusOK, rsp)
}

func (p *Post) CountMe(ctx *gin.Context) {
	rsp, err := p.PostClient.CountMe(ctx, &pp.PostRequest{
		Uid: ctx.Value("uid").(int64),
	})
	if err != nil {
		ctx.AbortWithStatusJSON(http.StatusBadRequest, err)
		return
	}

	ctx.JSON(http.StatusOK, rsp)
}

func (p *Post) Create(ctx *gin.Context) {
	form := new(pp.PostRequest)
	if err := ctx.Bind(form); err != nil {
		ctx.AbortWithStatus(http.StatusBadRequest)
		return
	}
	form.Uid = ctx.Value("uid").(int64)

	_, err := p.PostClient.Create(ctx, form)
	if err != nil {
		ctx.AbortWithStatusJSON(http.StatusBadRequest, err)
		return
	}

	ctx.JSON(http.StatusOK, "success")
}

func (p *Post) Toggle(ctx *gin.Context) {
	form := new(pp.PostRequest)
	if err := ctx.Bind(form); err != nil {
		ctx.AbortWithStatus(http.StatusBadRequest)
		return
	}

	_, err := p.PostClient.Toggle(ctx, form)
	if err != nil {
		ctx.AbortWithStatusJSON(http.StatusBadRequest, err)
		return
	}

	ctx.JSON(http.StatusOK, "success")
}
